# 数据库配置
import os
from flask_sqlalchemy import SQLAlchemy
import yaml

# 初始化SQLAlchemy
db = SQLAlchemy()

# 从配置文件加载数据库配置
def load_db_config(config_path='config.yml'):
    with open(config_path, 'r', encoding='utf-8') as file:
        config = yaml.safe_load(file)
        return config.get('database', {})

# 初始化数据库
def init_db(app):
    db_config = load_db_config()
    
    # 设置数据库连接URI
    if db_config.get('dialect', '').startswith('mysql'):
        app.config['SQLALCHEMY_DATABASE_URI'] = f"{db_config.get('dialect', 'mysql+pymysql')}://{db_config.get('username', 'root')}:{db_config.get('password', '')}@{db_config.get('host', 'localhost')}:{db_config.get('port', 3306)}/{db_config.get('database', 'repair_db')}"
    else:
        app.config['SQLALCHEMY_DATABASE_URI'] = f"{db_config.get('dialect', 'sqlite')}:///{db_config.get('database', 'db.sqlite')}"
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = db_config.get('track_modifications', False)
    
    # 初始化数据库
    db.init_app(app)

    # 初始化数据库
    with app.app_context():
        db.create_all()